package com.example.webapp.controller;

import com.example.webapp.entity.RequestGroup;
import com.example.webapp.entity.RequestLog;
import com.example.webapp.repository.RequestGroupRepository;
import com.example.webapp.repository.RequestLogRepository;
import com.example.webapp.service.RequestGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/request-history")
public class RequestHistoryController {

    @Autowired
    private RequestLogRepository requestLogRepository;

    @Autowired
    private RequestGroupRepository requestGroupRepository;

    @Autowired
    private RequestGroupService requestGroupService;

    @GetMapping
    public ResponseEntity<Page<RequestLog>> getRequestLogs(
            @RequestParam(required = false) String url,
            @RequestParam(required = false) String method,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        PageRequest pageRequest = PageRequest.of(page, size);
        Page<RequestLog> logs = requestLogRepository.findAll(pageRequest);
        return ResponseEntity.ok(logs);
    }

    @GetMapping("/group/{id}")
    public ResponseEntity<RequestGroup> getGroup(@PathVariable Long id) {
        Optional<RequestGroup> group = requestGroupRepository.findById(id);
        return group.map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @DeleteMapping("/group/{id}")
    public ResponseEntity<?> deleteGroup(@PathVariable Long id) {
        try {
            requestGroupService.deleteGroup(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            log.error("Error deleting group: ", e);
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
} 